package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/bson/primitive"

	"go.mongodb.org/mongo-driver/bson"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	mc, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017/coolcar?readPreference=primary&appname=mongodb-vscode%200.7.0&directConnection=true&ssl=false"))
	if err != nil {
		panic(err)
	}

	col := mc.Database("coolcar").Collection("account")
	findRows(col)
}

func insertRows(col *mongo.Collection) {
	res, err := col.InsertMany(context.Background(), []interface{}{
		bson.M{
			"open_id": "123",
		},
		bson.M{
			"open_id": "456",
		},
	})
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v, \n", res)
}

func findRow(col *mongo.Collection) {
	res := col.FindOne(context.Background(), bson.M{
		"open_id": "123",
	})
	var row struct {
		ID     primitive.ObjectID `bson:"_id"`
		OpenID string             `bson:"open_id"`
	}
	err := res.Decode(&row)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v, \n", row)
}

func findRows(col *mongo.Collection) {
	cur, err := col.Find(context.Background(), bson.M{})
	if err != nil {
		panic(err)
	}

	for cur.Next(context.Background()) {
		var row struct {
			ID     primitive.ObjectID `bson:"_id"`
			OpenID string             `bson:"open_id"`
		}
		err := cur.Decode(&row)
		if err != nil {
			panic(err)
		}
		fmt.Printf("%+v, \n", row)
	}
}
